<template>
  <view class="container position-relative w-100 h-100 overflow-hidden">
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar
      :fixed="false"
      :title="title"
      left-arrow
      @leftClick="$onClickLeft"
    />
    <!-- #endif -->
    <view class="exchange-box" v-if="current == 4">
      <view class="input-box">
        <input
          type="text"
          v-model="exchange_code"
          :placeholder="currentLanguageTexts.redemptionCodePlaceholder"
          placeholder-class="text-color-assist font-size-base"
        />
        <button type="primary" @click="exchange">
          {{ currentLanguageTexts.exchange }}
        </button>
      </view>
    </view>
    <view class="tabbar bg-white mb-1" v-else>
      <uv-tabs
        :list="tabs"
        :current="current"
        @change="change"
        keyName="title"
        :scrollable="false"
      ></uv-tabs>
    </view>
    <view class="flex-fill">
      <scroll-view
        scroll-y
        class="coupon-list"
        @scrolltolower="getCoupons(activeTabIndex)"
      >
        <view class="wrapper" v-if="4 != current">
          <uv-empty
            v-if="myCoupons.length == 0"
            :text="currentLanguageTexts.noData"
          ></uv-empty>
          <view
            class="coupon"
            v-for="(item, index) in myCoupons"
            :key="index"
            @tap="openDetailModal(item, index)"
          >
            <view class="taobao">
              <view class="ticket">
                <view class="left">
                  <image
                    class="picture"
                    :src="item.image"
                    mode="aspectFill"
                  ></image>
                  <view class="introduce">
                    <view class="top">
                      $
                      <text class="big">{{ item.value }}</text>
                      <view> 满{{ item.least }}减{{ item.value }} </view>
                    </view>
                    <view class="type">{{ item.title }}</view>
                    <view class="date u-line-1"
                      >{{ formatDateTime(item.startTime, 'YYYY-MM-DD') }}-{{
                        formatDateTime(item.endTime, 'YYYY-MM-DD')
                      }}</view
                    >
                  </view>
                </view>
                <view class="right">
                  <view
                    v-if="item.status == 0"
                    class="use immediate-use"
                    :round="true"
                    @tap="useCouponWith(item)"
                    >{{ currentLanguageTexts.immediateUse }}</view
                  >
                  <view v-else class="used">{{
                    currentLanguageTexts.usedAlready
                  }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="wrapper" v-if="4 == current">
          <uv-empty
            v-if="notCoupons.length == 0"
            :text="currentLanguageTexts.noData"
          ></uv-empty>
          <view
            class="coupon"
            v-for="(item, index) in notCoupons"
            :key="index"
            @tap="openDetailModal(item, index)"
          >
            <view class="taobao">
              <view class="ticket">
                <view class="left">
                  <image
                    class="picture"
                    :src="item.image"
                    mode="aspectFill"
                  ></image>
                  <view class="introduce">
                    <view class="top">
                      $
                      <text class="big">{{ item.value }}</text>
                      <view> 满{{ item.least }}减{{ item.value }} </view>
                    </view>
                    <view class="type">{{ item.title }}</view>
                    <view class="date u-line-1"
                      >{{ formatDateTime(item.startTime, 'YYYY-MM-DD') }}-{{
                        formatDateTime(item.endTime, 'YYYY-MM-DD')
                      }}</view
                    >
                  </view>
                </view>
                <view class="right">
                  <view
                    class="use immediate-use"
                    :round="true"
                    v-if="item.isReceive == 0"
                    @tap="receive(item, index)"
                    >{{ currentLanguageTexts.getCoupon }}</view
                  >
                  <view v-else class="used immediate-use">{{
                    currentLanguageTexts.receivedAlready
                  }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <modal
      custom
      :show="detailModalVisible"
      @cancel="closeDetailModal"
      width="90%"
    >
      <view class="modal-content">
        <view
          class="d-flex font-size-extra-lg text-color-base just-content-center mb-20"
          >{{ coupon.title }}</view
        >
        <view class="d-flex font-size-sm text-color-base mb-20">
          {{ currentLanguageTexts.periodOfValidity }}：{{
            formatDateTime(coupon.startTime, 'YYYY-MM-DD')
          }}-{{ formatDateTime(coupon.endTime, 'YYYY-MM-DD') }}
        </view>
        <view class="d-flex font-size-sm text-color-base mb-20">
          {{ currentLanguageTexts.receivedTime }}：{{
            formatDateTime(coupon.createTime)
          }}
        </view>
        <view class="d-flex font-size-sm text-color-base mb-20">
          {{ currentLanguageTexts.couponValue }}：满{{ coupon.least }}减{{
            coupon.value
          }}
        </view>
        <view
          class="d-flex font-size-sm text-color-base mb-20"
          v-if="activeTabIndex == 1"
        >
          {{ currentLanguageTexts.couponLimit }}：{{ coupon.limit }}
        </view>
        <view class="d-flex font-size-sm text-color-base mb-20">
          {{ currentLanguageTexts.scopeOfApplication }}：{{
            typeInfo(coupon.type)
          }}
        </view>
        <view class="d-flex font-size-sm text-color-base mb-20">
          {{ currentLanguageTexts.applicableStores }}：{{ coupon.shopName }}
        </view>
        <view
          class="d-flex align-items-center just-content-center"
          v-if="activeTabIndex == 0"
        >
          <button type="primary" @tap="useCoupon" class="use-coupon-btn">
            {{ currentLanguageTexts.immediateUse }}
          </button>
        </view>
        <view
          class="d-flex align-items-center just-content-center"
          v-if="activeTabIndex == 1"
        >
          <button
            type="primary"
            @tap="receive(coupon, couponIndex)"
            class="use-coupon-btn"
          >
            {{ currentLanguageTexts.getCoupon }}
          </button>
        </view>
      </view>
    </modal>

    <!--轻提示-->
    <uv-toast ref="uToast"></uv-toast>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import { onLoad, onShow, onPullDownRefresh, onHide } from '@dcloudio/uni-app';
import { formatDateTime, kmUnit } from '@/utils/util';
import { couponReceive, couponMine, couponIndexApi } from '@/api/coupon';

const main = useMainStore();
const { currentLanguageTexts } = storeToRefs(main);
const { isLogin } = storeToRefs(main);
const title = ref(currentLanguageTexts.value.discountCoupons);

const tabs = ref([
  {
    title: currentLanguageTexts.value.notUsed,
    page: 1,
    pagesize: 10,
    coupons: [],
  },
  {
    title: currentLanguageTexts.value.UsedAlready,
    page: 1,
    pagesize: 10,
    coupons: [],
  },
  {
    title: currentLanguageTexts.value.Expired,
    page: 1,
    pagesize: 10,
    coupons: [],
  },
]);
const activeTabIndex = ref(0);
const detailModalVisible = ref(false);
const coupon = ref({});
const couponIndex = ref(0);
const exchange_code = ref('');
const uToast = ref();
const myCoupons = ref([]);
const notCoupons = ref([]);
const current = ref(0);
//const type =

onLoad((option) => {
  if (!isLogin.value) {
    uni.navigateTo({ url: '/pages/components/pages/login/login' });
  }

  if (option.current) {
    current.value = option.current;
  }
  console.log('current.value:', current.value);
});
onShow(() => {
  getCoupons(current.value);
});
onPullDownRefresh(() => {
  if (activeTabIndex.value == 0) {
    myCoupons.value = [];
  }
  if (activeTabIndex.value == 1) {
    notCoupons.value = [];
  }
  tabs.value[activeTabIndex.value].page = 1;
  getCoupons(activeTabIndex.value);
});
watch(activeTabIndex, () => {
  getCoupons(activeTabIndex.value);
});

// tab栏切换
const change = (e) => {
  current.value = e.index;
  getCoupons();
};

// 兑换
const exchange = async () => {
  let data = await couponReceive({ code: exchange_code.value });
  if (data) {
    uToast.value.show({
      message: currentLanguageTexts.value.exchangeSuccessfully,
      type: 'success',
    });
    tabs.value[0].coupons = [];
    tabs.value[0].page = 1;
    getCoupons(0);
    tabs.value[1].coupons = [];
    tabs.value[1].page = 1;
    getCoupons(1);
  }
};
// 使用范围
const typeInfo = (type) => {
  if (type == 0) {
    return currentLanguageTexts.value.general;
  }
  if (type == 1) {
    return currentLanguageTexts.value.takein;
  }
  if (type == 2) {
    return currentLanguageTexts.value.takeout;
  }
};
const handleTab = (index) => {
  activeTabIndex.value = index;
};
const getCoupons = async (type) => {
  let page = 1;
  let pagesize = 10;
  // 我的优惠券
  let data = [];
  // 未领优惠券
  if (type == 4) {
    notCoupons.value = await couponIndexApi({ page: page, pagesize: pagesize });
  } else {
    myCoupons.value = await couponMine({
      page: page,
      pagesize: pagesize,
      type: current.value,
    });
  }
  uni.stopPullDownRefresh();
};
const openDetailModal = (coupon2, index) => {
  couponIndex.value = index;
  coupon.value = coupon2;
  detailModalVisible.value = true;
};
const useCouponWith = (coupon) => {
  //coupon.value = coupon
  useCoupon();
};
const closeDetailModal = () => {
  detailModalVisible.value = false;
  coupon.value = {};
};
const useCoupon = () => {
  uni.switchTab({
    url: '/pages/menu/menu',
  });
};
const showTip1 = () => {
  uni.showToast({
    title: currentLanguageTexts.value.couponsYet,
    icon: 'none',
  });
};
const showTip2 = () => {
  uni.showToast({
    title: currentLanguageTexts.value.codeYet,
    icon: 'none',
  });
};
// 领取优惠券
const receive = async (coupon, index) => {
  let data = await couponReceive({ id: coupon.id });
  if (data) {
    uToast.value.show({
      message: currentLanguageTexts.value.ReceivedSuccessfully,
      type: 'success',
    });
    detailModalVisible.value = false;

    getCoupons(4);
  }
};
</script>

<style lang="scss" scoped>
/* #ifdef H5 */
page {
  height: 100%;
}
/* #endif */

.container {
  display: flex;
  flex-direction: column;
}

.exchange-box {
  flex-shrink: 0;
  height: 200rpx;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .input-box {
    display: flex;
    align-items: stretch;
    width: 70%;
    flex-shrink: 0;
    input {
      flex: 1;
      height: 80rpx;
      border: 1rpx solid #eee;
      border-right: 0;
      border-radius: 8rpx 0 0 8rpx;
      // padding: 20rpx;
      font-size: $font-size-base;
      color: $text-color-base;
    }
    button {
      border-radius: 0 8rpx 8rpx 0;
      display: flex;
      align-items: center;
    }
  }
}

.bottom-box {
  height: 80rpx;
  flex-shrink: 0;
  .item {
    padding: 0 20rpx;
    position: relative;

    &::after {
      content: ' ';
      border-right: 1rpx solid $text-color-assist;
      height: 100%;
      position: absolute;
      right: 0;
      top: 0;
      transform: scaleX(0.5) scaleY(0.8);
    }

    &:nth-last-child(1)::after {
      border-right: 0;
    }
  }
}

.coupon-list {
  height: calc(100vh - 120rpx - 200rpx);
  /* #ifdef H5 */
  height: calc(100vh - 120rpx - 200rpx - 44px);
  /* #endif */
}

.wrapper {
  padding: 10rpx 20rpx;
  display: flex;
  flex-direction: column;

  .coupon {
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    margin-bottom: 30rpx;
    //padding: 0 30rpx;
    border-radius: 6rpx;
    box-shadow: 0 10rpx 10rpx -10rpx rgba(15, 15, 15, 0.1);
    position: relative;

    &::before {
      content: '';
      position: absolute;
      background-color: $bg-color;
      width: 30rpx;
      height: 30rpx;
      bottom: 65rpx;
      left: -15rpx;
      border-radius: 100%;
    }

    &::after {
      content: '';
      position: absolute;
      background-color: $bg-color;
      width: 30rpx;
      height: 30rpx;
      bottom: 65rpx;
      right: -15rpx;
      border-radius: 100%;
    }

    .detail {
      padding: 20rpx 0;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        border-bottom: 1rpx dashed #c6c6c6;
        transform: scaleY(0.5);
      }

      .coupon-img {
        width: 150rpx;
        height: 150rpx;
        margin-right: 40rpx;
      }
    }
  }
}

.use-coupon-btn {
  width: 95%;
  border-radius: 50rem !important;
}

.taobao {
  background-color: white;
  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    .left {
      display: flex;
      align-items: center;
    }
    .store {
      font-weight: 500;
    }
    .buddha {
      width: 70rpx;
      height: 70rpx;
      border-radius: 10rpx;
      margin-right: 10rpx;
    }
    .entrance {
      color: $uv-info;
      border: solid 2rpx $uv-info;
      line-height: 48rpx;
      padding: 0 30rpx;
      background: none;
      border-radius: 15px;
    }
  }
  .ticket {
    display: flex;
    .left {
      width: 70%;
      padding: 20rpx;
      background-color: white; //rgb(255, 245, 244);
      border-radius: 20rpx;
      border-right: dashed 2rpx rgb(224, 215, 211);
      display: flex;
      .picture {
        //width: 172rpx;
        border-radius: 20rpx;
        width: 190rpx;
        height: 190rpx;
      }
      .introduce {
        margin-left: 10rpx;
        .top {
          color: $uv-warning;
          font-size: 28rpx;
          .big {
            font-size: 60rpx;
            font-weight: bold;
            margin-right: 10rpx;
          }
        }
        .type {
          font-size: 28rpx;
          color: $uv-info-dark;
        }
        .date {
          margin-top: 10rpx;
          font-size: 20rpx;
          color: $uv-info-dark;
        }
      }
    }
    .right {
      width: 30%;
      padding: 40rpx 20rpx;
      background-color: white; //rgb(255, 245, 244);
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      .use {
        height: auto;
        padding: 0 20rpx;
        font-size: 24rpx;
        border-radius: 40rpx;
        color: #ffffff !important;
        background-color: $uv-warning !important;
        line-height: 40rpx;
        color: rgb(117, 142, 165);
        margin-left: 20rpx;
      }
      .used {
        height: auto;
        padding: 0 20rpx;
        font-size: 24rpx;
        border-radius: 40rpx;
        color: #ffffff !important;
        background-color: $uv-info-dark !important;
        line-height: 40rpx;
        color: rgb(117, 142, 165);
        margin-left: 20rpx;
      }
    }
    .right_log {
      text-align: center;
      width: 30%;
      padding: 80rpx 0rpx;
      background-color: white; //rgb(255, 245, 244);
      border-radius: 20rpx;

      align-items: center;
    }
  }
}
</style>
